#!/usr/bin/env python3
"""
翻译引擎使用示例
展示如何使用不同的适配器进行音频翻译
"""

import os
import sys
import logging
from pathlib import Path

# 添加项目根目录到Python路径
project_root = Path(__file__).parent.parent
sys.path.insert(0, str(project_root))

from core.translation_factory import TranslationEngineFactory
from config.translation_config import get_translation_config, get_current_engine_type

# 配置日志
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

def test_whisper_marian():
    """测试WhisperMarian分步处理适配器"""
    logger.info("=== 测试 WhisperMarian 分步处理适配器 ===")
    
    try:
        # 创建引擎
        engine = TranslationEngineFactory.create_engine("whisper_marian")
        
        # 检查就绪状态
        if not engine.is_ready():
            logger.error("WhisperMarian引擎未就绪")
            return False
        
        # 获取支持的语言
        languages = engine.get_supported_languages()
        logger.info(f"支持的语言: {languages}")
        
        # 测试音频翻译（需要提供音频文件路径）
        # audio_path = "path/to/audio.wav"
        # result = engine.translate_audio(
        #     audio_path=audio_path,
        #     source_lang="zh",
        #     target_lang="en",
        #     enable_translation=True
        # )
        # logger.info(f"翻译结果: {result}")
        
        logger.info("WhisperMarian适配器测试成功")
        return True
        
    except Exception as e:
        logger.error(f"WhisperMarian适配器测试失败: {e}")
        return False

def test_seamless_m4t():
    """测试SeamlessM4T端到端适配器"""
    logger.info("=== 测试 SeamlessM4T 端到端适配器 ===")
    
    try:
        # 创建引擎
        engine = TranslationEngineFactory.create_engine("seamless_m4t")
        
        # 检查就绪状态
        if not engine.is_ready():
            logger.error("SeamlessM4T引擎未就绪")
            return False
        
        # 获取支持的语言
        languages = engine.get_supported_languages()
        logger.info(f"支持的语言: {languages}")
        
        logger.info("SeamlessM4T适配器测试成功")
        return True
        
    except Exception as e:
        logger.error(f"SeamlessM4T适配器测试失败: {e}")
        return False

def test_triton():
    """测试Triton Inference Server适配器"""
    logger.info("=== 测试 Triton Inference Server 适配器 ===")
    
    try:
        # 创建引擎
        engine = TranslationEngineFactory.create_engine(
            "triton",
            server_url="localhost:8001",
            model_name="whisper_asr",
            protocol="grpc"
        )
        
        # 检查就绪状态
        if not engine.is_ready():
            logger.error("Triton引擎未就绪")
            return False
        
        # 获取模型信息
        model_info = engine.get_model_info()
        logger.info(f"模型信息: {model_info}")
        
        logger.info("Triton适配器测试成功")
        return True
        
    except Exception as e:
        logger.error(f"Triton适配器测试失败: {e}")
        return False

def test_engine_switching():
    """测试引擎切换功能"""
    logger.info("=== 测试引擎切换功能 ===")
    
    try:
        config = get_translation_config()
        
        # 显示当前配置
        summary = config.get_config_summary()
        logger.info(f"当前配置: {summary}")
        
        # 切换到SeamlessM4T
        config.set_engine_type("seamless_m4t")
        logger.info(f"切换到: {config.get_engine_type()}")
        
        # 创建新引擎
        engine = TranslationEngineFactory.create_engine(
            config.get_engine_type(),
            **config.get_engine_config()
        )
        
        if engine.is_ready():
            logger.info("引擎切换成功")
            return True
        else:
            logger.error("引擎切换失败")
            return False
            
    except Exception as e:
        logger.error(f"引擎切换测试失败: {e}")
        return False

def test_factory_methods():
    """测试工厂类方法"""
    logger.info("=== 测试工厂类方法 ===")
    
    try:
        # 获取可用引擎
        available_engines = TranslationEngineFactory.get_available_engines()
        logger.info(f"可用引擎: {available_engines}")
        
        # 获取引擎信息
        for engine_type in available_engines.keys():
            info = TranslationEngineFactory.get_engine_info(engine_type)
            logger.info(f"{engine_type} 信息: {info}")
        
        # 验证配置
        for engine_type in available_engines.keys():
            is_valid = TranslationEngineFactory.validate_engine_config(engine_type, {})
            logger.info(f"{engine_type} 配置验证: {is_valid}")
        
        logger.info("工厂类方法测试成功")
        return True
        
    except Exception as e:
        logger.error(f"工厂类方法测试失败: {e}")
        return False

def main():
    """主函数"""
    logger.info("开始翻译引擎测试...")
    
    # 测试结果
    results = {}
    
    # 测试各个适配器
    results["whisper_marian"] = test_whisper_marian()
    results["seamless_m4t"] = test_seamless_m4t()
    results["triton"] = test_triton()
    
    # 测试引擎切换
    results["engine_switching"] = test_engine_switching()
    
    # 测试工厂方法
    results["factory_methods"] = test_factory_methods()
    
    # 显示测试结果
    logger.info("\n=== 测试结果汇总 ===")
    for test_name, success in results.items():
        status = "✅ 成功" if success else "❌ 失败"
        logger.info(f"{test_name}: {status}")
    
    # 统计成功率
    success_count = sum(results.values())
    total_count = len(results)
    success_rate = (success_count / total_count) * 100
    
    logger.info(f"\n总体成功率: {success_count}/{total_count} ({success_rate:.1f}%)")
    
    if success_rate >= 80:
        logger.info("🎉 大部分测试通过，系统运行正常")
    elif success_rate >= 50:
        logger.info("⚠️  部分测试通过，系统基本可用")
    else:
        logger.error("❌ 大部分测试失败，系统需要检查")

if __name__ == "__main__":
    main()




